/*
 * Server.cpp
 *
 *  Created on: May 8, 2013
 *      Author: ken
 */

#include "Server.hpp"
#include "CommandCodes.hpp"
#include "ServerStates.hpp"
#include "ServerConnection.hpp"
#include "ClientConnection.hpp"
#include "Config.hpp"
#include "Logger.hpp"
#include "sys/wait.h"

int main(int argc, char **argv) {
	Logger::getInstance().log("Starting up...");
	//Config::getInstance().writeToFile();
	Config::getInstance().readFromFile();
	Server();
	return 0;
}

Server::Server() {
	//Ignore child signal: no lost processes anymore
	signal(SIGCHLD, SIG_IGN );

	//create server socket
	ServerConnection sc;

	while (true) {
		Logger::getInstance().log("Waiting for client");
		ServerStates sCom(sc.waitForClient());

		pid_t pID = fork();
		if (pID == 0) { // child
			sCom.handleClient();
			exit(0);
		} else if (pID < 0) { // failed to fork
			Logger::getInstance().log("Failed to fork");
			exit(1);
		}
	}
}

Server::~Server() {
}
